// const CircularDependencyPlugin = require('circular-dependency-plugin')
const FileManagerPlugin = require('filemanager-webpack-plugin')
const { defineConfig } = require('@vue/cli-service')
const path = require('path')
const packInfo = require('./package.json')
const TerserPlugin = require('terser-webpack-plugin')

const imgSourceMaxSize = 10 // 10M
const packageZipName = `../${packInfo.name}@${packInfo.version}.zip`

module.exports = defineConfig({
    publicPath: `/${packInfo.name}/`,
    outputDir: packInfo.name,
    productionSourceMap: false,
    chainWebpack: (config) => {
        // 注入 scss 变量
        // const types = ['vue-modules', 'vue', 'normal-modules', 'normal']
        // types.forEach((type) => addStyleResource(config.module.rule('scss').oneOf(type)))

        // micro-app 标签排除警告
        config.module
            .rule('vue')
            .use('vue-loader')
            .tap((options) => {
                options.compilerOptions = {
                    ...(options.compilerOptions || {}),
                    isCustomElement: (tag) => /^micro-app/.test(tag)
                }
                return options
            })

        // 资源内联
        config.module.rule('images').set('parser', {
            dataUrlCondition: {
                maxSize: imgSourceMaxSize * 1024 * 1024
            }
        })

        // 打包压缩包
        config.when(process.env.NODE_ENV === 'production', (config) =>
            config
                .plugin('FileManagerPlugin')
                .use(FileManagerPlugin, [
                    {
                        events: {
                            onEnd: [
                                {
                                    // 首先需要删除项目根目录下的压缩包
                                    delete: [packageZipName],
                                    copy: [
                                        {
                                            source: `./${packInfo.name}`,
                                            destination: `./${packInfo.name}_temp/${packInfo.name}`
                                        }
                                    ]
                                },
                                {
                                    // 然后我们选择 packInfo.name 文件夹将之打包成 packInfo.name.zip 并放在根目录
                                    archive: [
                                        {
                                            source: `./${packInfo.name}_temp`,
                                            destination: packageZipName
                                        }
                                    ]
                                },
                                {
                                    delete: [`./${packInfo.name}_temp`]
                                }
                            ]
                        }
                    }
                ])
                .end()
        )

        // SourceMap 生成
        config.when(process.env.NODE_ENV === 'development', (config) =>
            config.output.devtoolModuleFilenameTemplate((info) => {
                const resPath = info.resourcePath
                if (
                    (/\.vue$/.test(resPath) && !/type=script/.test(info.identifier)) ||
                    /node_modules/.test(resPath)
                ) {
                    return `${packInfo.name}:///${resPath}?${info.hash}`
                }
                return `${packInfo.name}:///${resPath.replace('./src', 'my_source/src')}`
            })
        )

        // 打包（压缩）时，去除 console，可减小打包体积
        config.optimization.minimizer('terser').use(TerserPlugin, [
            {
                terserOptions: {
                    compress: { pure_funcs: ['console.log', 'console.warn'] }
                }
            }
        ])
    },

    configureWebpack: {
        experiments: {
            topLevelAwait: true
        },
        resolve: {
            alias: {
                '@': path.resolve(__dirname, 'src'),
                '@ROOT': path.resolve(__dirname)
            }
        },
        externals: {
            vue: 'Vue',
            'vue-router': 'VueRouter',
            vuex: 'Vuex',
            'element-plus': 'ElementPlus',
            '@element-plus/icons-vue': 'ElementPlusIconsVue',
            lodash: '_',
            'resize-observer-polyfill': 'ResizeObserver',
            'xlsx': 'XLSX',
            'echarts': 'echarts',
            'jn-ve-global': 'VeGlobal',
            '@jsjn/icons-vue': 'JnIconsVue'
        },
        plugins: [
            // 寻找循环引用的插件
            // new CircularDependencyPlugin({
            //     exclude: /node_modules/,
            //     include: /src/,
            //     failOnError: true,
            //     allowAsyncCycles: false,
            //     cwd: process.cwd()
            // })
        ]
    },

    devServer: {
        port: packInfo.port,
        open: false,
        headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
            'Access-Control-Allow-Headers': 'X-Requested-With, content-type, Authorization'
        },
        client: {
            overlay: {
                runtimeErrors: false,
                warnings: false,
                errors: false
            }
        }
    }
})

// function addStyleResource(rule) {
//     rule.use('style-resource')
//         .loader('style-resources-loader')
//         .options({
//             patterns: [path.resolve(__dirname, '../_core/assets/styles/variable.scss')]
//         })
// }
